//
//  GiveRiceVC.swift
//  zhonglb_iOS
//
//  Created by lxm on 2021/12/1.
//

import UIKit
import RxRelay
import HandyJSON

class TransferInput: ZMViewController, UITextFieldDelegate {
    
    //MARK:--------------------属性--------------------
    var ratio = ZMUtil.fastNilBehavior(type: Double.self)
    
    var inteRatio = ZMUtil.fastNilBehavior(type: Double.self)
    // 当前选中的好友
    var currentUser : BehaviorRelay<UserModel?> = BehaviorRelay(value: nil)
        
    let wallet = ZMUtil.fastNilBehavior(type: MineModels.WalletInfo.self)

    var transferModel = TransferModel()
    // 1 个人 2商城
    var type = 1
    //MARK:--------------------UI控件--------------------
    @IBOutlet weak var moneyText: UITextField!
        
    @IBOutlet weak var handFee: UILabel!
    
    @IBOutlet weak var topTip: UILabel!
    
    @IBOutlet weak var selectContainer: UIView!
    
    @IBOutlet weak var qxz: UILabel!
    
    @IBOutlet weak var userV: UIView!
    
    @IBOutlet weak var avatar: UIImageView!
    
    @IBOutlet weak var nickname: UILabel!
    
    @IBOutlet weak var showid: UILabel!
    
    @IBOutlet weak var sureButton: UIButton!
        
    @IBOutlet weak var codeText: UITextField!
    
    @IBOutlet weak var codeButton: UIButton!
    
    @IBOutlet weak var balance: UILabel!
    
    
    @IBOutlet weak var needIntegral: UILabel!
    
    var loading = XMLoadingView()
    
    //MARK:--------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        loading.showInView(fatherView: view)
        setUI()
        addConstraints()
        bindAction()
        loadWallet()
    }
    
    //MARK:--------------------UI--------------------
    func setUI() {
        title = "转账"
        moneyText.delegate = self
        let tap = UITapGestureRecognizer()
        tap.addTarget(self, action: #selector(selectUser))
        selectContainer.addGestureRecognizer(tap)
        codeText.delegate = InputMananger.shard.onlyNumber
        transferModel.userId = ZMAppShareData.share.safeUserId
    }
    
    func addConstraints() {

    }
    
    //MARK:--------------------methods--------------------
  
    func calculate() -> (ratio : NSDecimalNumber, banlance : NSDecimalNumber, handFee : NSDecimalNumber, money : NSDecimalNumber)? {
        let money = NSDecimalNumber.init(string: moneyText.text!)
        guard money.doubleValue > 0, let wallet = self.wallet.value, let ratioNum = self.ratio.value else {
            return nil
        }
        let ratio = NSDecimalNumber.init(value: ratioNum)
        let banlance = NSDecimalNumber.init(value: wallet.balance)
        let handFee = money.multiplying(by: ratio).dividing(by: NSDecimalNumber.init(value: 100)).rounding(accordingToBehavior: ZMUtil.DecimalNumberHandler(roundingMode: .plain, scale: 4))
        return (ratio : ratio, banlance : banlance, handFee : handFee, money : money)
    }
    
    func bindAction() {
        Observable.combineLatest(moneyText.rx.text.orEmpty,
                                 currentUser,
                                 codeText.rx.text.orEmpty).subscribe(onNext:{ [unowned self] resp in
            guard let r = self.calculate()
            else {
               self.setPayButtonEnable(enable: false)
                var str = "手续费：\(self.ratio.value ?? 0)%"
                self.handFee.text = str
               return
            }
            let ok = r.handFee.adding(r.money).compare(r.banlance) == .orderedAscending && resp.1 != nil && resp.2.count == 6
            self.setPayButtonEnable(enable: ok)
            var str = "手续费：\(r.handFee.stringValue) (\(r.ratio.stringValue)%)"
            self.handFee.text = str
        }).disposed(by: disposeBag)
 
        
        currentUser.subscribe(onNext:{ [unowned self] resp in
            if let r = resp {
                self.avatar.zm.setImage(urlStr: r.avatar)
                self.nickname.text = r.nickname
                self.showid.text = "手机号：" + r.phone.zm.hidPhone()
                self.showid.isHidden = false
            } else {
                self.showid.isHidden = true
                self.nickname.text = "选择转账给"
            }
        }).disposed(by: disposeBag)
        
        wallet.subscribe(onNext:{ [unowned self] resp in
            if let resp = resp {
                self.balance.text = "可用余额：" + resp.balance.zm.toString(keep: 4)
            }
        }).disposed(by: disposeBag)
        
        ratio.subscribe(onNext:{ [unowned self] resp in
            if let resp = resp {
                self.handFee.text = "手续费：\(resp)%"
            }
        }).disposed(by: disposeBag)
        
        inteRatio.subscribe(onNext:{ [unowned self] resp in
            if let resp = resp {
                self.needIntegral.text = "消耗积分：\(resp.zm.toString(keep: 4))"
                self.needIntegral.isHidden = resp == 0
            }
        }).disposed(by: disposeBag)
    }
    
    @objc
    func selectUser() {
        let vc = TransFerSearch()
        self.navigationController?.pushViewController(vc, animated: true)
        vc.onSelect = { user in
            self.currentUser.accept(user)
        }
    }

    @IBAction func onSure(_ sender: Any) {
        if !ZMAppShareData.share.safeUserInfo.isTradeOk {
            // 判断是否设置交易密码
            ZMAlertView.show(content: "还未设置交易密码", left: "关闭", right: "马上去设置") {
                
            } onRight: {
                let cls = Swift.type(of: self)
                MineService.shared.tradeSuccessToVC = cls
                let vc = TradeFroget()
                self.navigationController?.pushViewController(vc, animated: true)
            }
            return
        }
        realTransfer()
    }
    
    func realTransfer() {
        guard let r = calculate(),
                let currentUser = currentUser.value,
                let inteRatio = inteRatio.value
        else {return}
        transferModel.otherUserId = currentUser.uid
        transferModel.type = type
        transferModel.serviceFee = r.handFee.stringValue
        transferModel.money = r.money.stringValue
        
        // 发起提现请求
        let typeStr = "TRANSACTION"
        
        let leftStr = inteRatio == 0 ? "服务费：￥\(r.handFee.stringValue) 费率：\(r.ratio.stringValue)% " : "服务费：￥\(r.handFee.stringValue) 费率：\(r.ratio.stringValue)%  消耗积分：\(inteRatio.zm.toString(keep: 4))"
        
        CommonService.shared.showPsdInput(title : "确认转账", money: r.money.adding(r.handFee).stringValue, left : leftStr, right : "") { psd, close in
            self.transferModel.tradePwd = psd
            // 创建将军令
            ZMToast.showActivity()
            MineAPI.create_auth_code(["id" : "1","userId":ZMAppShareData.share.safeUserId, "type":typeStr]).rxRequest(type: String.self).flatMapLatest { r ->  Observable<Any?> in
                // 生成本地将军令
                let code = AppHelper.generalOrder(userId: "\(ZMAppShareData.share.safeUserId)",
                                                  randomKey: ZMAppShareData.share.loginInfo!.token,
                                                  showId: ZMAppShareData.share.safeUserInfo.showId,
                                                  time: Int(r) ?? 0,
                                                  type: typeStr, id: "1")
                let pa = [
                    "code" : code,
                    "encryptedContent" : self.encryptParams(),
                    "captcha" : self.codeText.text!,
                    "userId" : ZMAppShareData.share.safeUserId,
                ] as [String : Any]
                return MineAPI.transfer(pa).rxRequestNullAble(type: Any.self)
            }.subscribe(onNext:{ [unowned self] resp in
                // 成功
                ZMToast.showToast(title: "转账成功")
                close(true)
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    self.navigationController?.popViewController(animated: true)
                }
                ZMNotification.shard.subject.onNext(type == 2 ? .updateVIPMallBankInfo : .updateBalance)
            }, onError: { e in
                close(false)
            }).disposed(by: self.disposeBag)
        }
    }
    
    func encryptParams() -> String {
        guard let json = self.transferModel.toJSONString() else {return ""}
        let after = ZMOcHelper.encrypt(json, key: theKey)
        return after
    }
    
    @IBAction func onSendMessage(_ sender: UIButton) {
        LoginService.shared.showVerifycation(vc: self) { success in
            if success {
                self.sendMsg()
            }
        }
    }
    
    func sendMsg() {
        ZMToast.showActivity()
        guard let phone = ZMAppShareData.share.userInfo.value?.phone else {
            ZMToast.showToast(title: "电话信息出错")
            return
        }
        ZMAPIManage<Any>().sendReqeust(method: LoginAPI.sendCode(["phone":phone, "type":"7"])) { (resp) in
            if resp.code == .success {
                ZMToast.hiddenActivity()
                self.codeButton.zm.countDown(count: 60)
                self.codeText.becomeFirstResponder()
            }
        }
    }
    
    func loadWallet() {
        let api : ZMApiProvider = type == 2 ? VIPMallAPI.walletInfo([:]) : MineAPI.walletInfo([:])
        Observable.combineLatest(MineAPI.transferRatio(["type" : type]).rxRequest(type: [String : Any].self), api.rxRequest(type: MineModels.WalletInfo.self)).subscribe(onNext:{ [unowned self] resp in
            self.ratio.accept(JSON(resp.0)["serviceFee"].doubleValue)
            self.inteRatio.accept(JSON(resp.0)["integralFee"].doubleValue)
            self.wallet.accept(resp.1)
            self.loading.hideView(anmation: true)
        }, onError: { e in
            self.loading.showError(e.localizedDescription)
        }).disposed(by: disposeBag)
    }
    
    // 将支付按钮设置为可用?
    func setPayButtonEnable(enable : Bool) {
        self.sureButton.isEnabled = enable
        self.sureButton.backgroundColor = enable ? Style.mainColor : UIColor.zm.colorCCCCCC()
    }
    
    //MARK:--------------------delegate--------------------
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let oldStr = textField.text
        let nsOldStr = oldStr! as NSString
        let newStr = nsOldStr.replacingCharacters(in: range, with: string)
        return (newStr.zm.match("\\d{0,10}\\.?\\d{0,4}") || newStr.count == 0)
    }
}



//MARK: model
extension TransferInput {
    class UserModel : HandyJSON {
        required init(){}
        var avatar = ""
        var money = 0.0
        var nickname = ""
        var phone = ""
        var serviceFee = 0.0
        var showId = ""
        var totalMoney = 0.0
        var uid = 0
        var createTime = ""
        
        var isSelect = false
    }
    
    struct TransferModel : HandyJSON {
//        加密字段内容：{类型[1个人 2商城]：Integer type支付密码：String tradePwd发送方：Integer userId接收方：Integer otherUserId转账金额：BigDecimal money手续费(四舍五入保留两位小数)：BigDecimal serviceFee}
        var type = 0
        var tradePwd = ""
        var userId = 0
        var otherUserId = 0
        var money = ""
        var serviceFee = ""
    }
}
